package edu.fpa.day0722;

public class SetHashMap5<K,V> {
    Node2[] table;


    public SetHashMap5(){
        table = new Node2[16];
    }

    public void put(K key,V value) {
        Node2 newNode = new Node2();
        newNode.hash = Myhash(key.hashCode(),table.length);
        newNode.key = key;
        newNode.value = value;
        newNode.next = null;

        Node2 node1 = table[newNode.hash];
        boolean keyreapt =false;
        Node2 node2 = null;
        if(node1==null) {
            table[newNode.hash] = newNode;
        }else {
            while(node1!=null) {
                if(node1.key.equals(key)) {
                    keyreapt = true;
                    node1.value = value;
                    break;
                }else {
                    if(node1!=null)
                        node2 = node1;
                    node1 = node1.next;
                }
                if(!keyreapt) {
                    node2.next = newNode;
                }
            }
        }

    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("{") ;
        for(int i=0;i<table.length;i++) {
            Node2 node = table[i];
            while(node!=null) {
                sb.append(node.key+":"+node.value+",");
                node = node.next;
            }
        }
        sb.setCharAt(sb.length()-1, '}');
        return sb.toString();
    }
    public static int Myhash(int index,int length) {
        return index&(length-1);
    }
    public Object get(K key) {
        int hash = Myhash(key.hashCode(),table.length);
        Object value = null;
        Node2 node = table[hash];
        while(node!=null) {
            if(node.key.equals(key)) {
                return node.value;
            }
            node = node.next;
        }
        return value;
    }
    public void remove(K key) {
        int hash = Myhash(key.hashCode(),table.length);
        Node2 node = table[hash];
        Node2 node3 = null;
        if(node!=null) {
            if(node.key.equals(key)) {
                table[hash] = node.next;
            }
            else {node3 = node.next;
                Node2 node4 = node;
                while(node3!=null)
                    if(node3.key.equals(key)){
                        node4.next = node3.next;
                    }
                node4 = node3;
                node3 = node3.next;
            }
        }
    }
    public static void main(String[] args) {
        SetHashMap5<Integer,String> s = new SetHashMap5<>();
        s.put(10,"aa");
        s.put(20, "bb");
        s.put(30, "cc");
        s.put(20, "bbdd");
        s.put(53, "ee");
        s.put(85, "ff");
        System.out.println(s);
        System.out.println(s.get(20));
        s.remove(10);
        System.out.println(s);
    }
}